package org.carota.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import lombok.extern.slf4j.Slf4j;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : AnWen
 * @version :1.0
 * @email : anwen375@qq.com
 * @since : 2023-03-27 9:20
 */
@Slf4j
public class QrCodeUtils {

    public static void generateQrCodeImage(String text, int width, int height, String filePath) {
        try {
            BitMatrix bitMatrix = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, width, height);
            MatrixToImageWriter.writeToPath(bitMatrix, "PNG", Paths.get(filePath));
        } catch (WriterException | IOException e) {
            log.error("生成二维码失败:", e);
        }
    }

    /**
     * 生成二维码
     *
     * @param contents 二维码的内容
     * @param width    二维码图片宽度
     * @param height   二维码图片高度
     */
    public static BufferedImage createQrCodeBufferImage(String contents, int width, int height) {
        Map<EncodeHintType, Object> hints = new HashMap<> ();
        hints.put(EncodeHintType.CHARACTER_SET, StandardCharsets.UTF_8.name());
        try {
            BitMatrix bitMatrix = new QRCodeWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints);
            return MatrixToImageWriter.toBufferedImage(bitMatrix);
        } catch (WriterException e) {
            log.error("生成二维码失败:", e);
            return null;
        }
    }


}
